package StudyCode.summary.csv;

import java.util.Arrays;
import java.util.Collection;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ObjectsToCSVString {
	public static final char COMMA_CHAR = ',';
	public static final String NULL = "null";


	public static void main(String[] args) {
		Object[] objects = new Object[3];
		objects[0] = "www";
		objects[1] = "tah1986";
		objects[2] = "com";
		System.out.println(Arrays.toString(objects));
		System.out.println("对象转为CSV字符串");
		System.out.println(getCSVPhrase(objects));
	}

	public static String getCSVPhrase(Collection<?> objects) {
		return getCSVPhrase(objects, COMMA_CHAR);
	}


	public static String getCSVPhrase(Collection<?> objects, char separator) {
		return getCSVPhrase(objects, String.valueOf(separator));
	}


	public static String getCSVPhrase(Collection<?> objects,
	                                  String separator) {
		StringBuilder s = new StringBuilder();
		if (!objects.isEmpty()) {
			for (Object o : objects) {
				if (o != null) {
					s.append(o.toString());
				} else {
					s.append(NULL);
				}
				s.append(separator);
			}
			s.setLength(s.length() - separator.length());
		}
		return s.toString();
	}


	public static String getCSVPhrase(Object[] objects) {
		return getCSVPhrase(objects, COMMA_CHAR);
	}


	public static String getCSVPhrase(Object[] objects, char separator) {
		return getCSVPhrase(objects, String.valueOf(separator));
	}


	public static String getCSVPhrase(Object[] objects, String separator) {
		StringBuilder s = new StringBuilder();
		if (objects.length > 0) {
			for (Object o : objects) {
				if (o != null) {
					s.append(o.toString());
				} else {
					s.append(NULL);
				}
				s.append(separator);
			}
			s.setLength(s.length() - separator.length());
		}
		return s.toString();
	}
}
